package fireway;

/**
 * 求一个数的乘方
 * 2018年 07月 08日 星期日
 *
 * @author fireway
 */
public class Math {
    private static final boolean DEBUG = false;
    /**
     * Don't let anyone instantiate this class.
     */
    private Math() {}

    /**
     * the value <code>x<sup>y</sup></code>
     */
    public static int pow(int x, int y) {
        if (DEBUG) {
            System.out.println("Entering x[" + x + "], y[" + y + "]");
        }

        if (y < 0) {
            System.out.println("error: y is less than 0!!!");
            return 0;
        }

        if (0 == y) {
            return 1;
        }


        if (0 == x || 1 == x || 1 == y) {
            return x;
        }

        if (y % 2 == 1) {
            int temp = pow(x * x, y / 2) * x;
            if (DEBUG) {
                System.out.println("Returning " + temp + ", x[" + x + "], y[" + y + "]");
            }
            return temp;
        } else {
            int temp = pow(x * x, y / 2);
            if (DEBUG) {
                System.out.println("Returning " + temp + ", x[" + x + "], y[" + y + "]");
            }
            return temp;
        }
    }
}
